﻿using CKS.PLC.Action.System;
using CKS.PLC.Core.CronJob;
using FreeSql;
using Infrastructure;
using Microsoft.Extensions.DependencyInjection;
using PrintMark.Helper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZR.Model.Models.ProductionControl;

namespace CKS.PLC.Action.Subscription
{
    /// <summary>
    /// 打印面单
    /// 打印面单需要调用客户的wss服务
    /// </summary>
    public class Work04Action: SaveProcessingResults
    {
        WssPrintClient WssPrintClient;
        public Work04Action(DecodeValue _value) : base(_value)
        {
            WssPrintClient = InternalApp.JobProvider.GetService<MonitorClientJob>().WssPrintClient;
        }

        public override AfterSaveResult AfterSaved(SaveArg e)
        {
            string TaskNo = Value.GetLinkData(1).ToString();
            var act = e.CksAction;
            var replyPos = Value.GetReplyPosition(act.WriteDB, act.ActionId, act.ActionKey);

            

            //查出任务，修改任务的状态
            var task = conn.Select<CksPackagingTask>()
                .Where(a => a.TaskNo == TaskNo).First();

            //如果任务不存在直接返回错误
            var fsqlTable = e.TableInfo;
            var dict = new Dictionary<string, object>();
            dict["Id"] = e.InsertIdentityId;
            dict["CheckResult"] = "2";
            if (task == null)
            {
                dict["Info"] = $"任务编号不存在:{TaskNo}";
                dict["TaskNo"] = TaskNo;
                UpdateDynamicTableData(fsqlTable, dict);
                EventBus.AddLog($"任务编号{TaskNo}不存在");
                SiemensClient.SetValue(replyPos, "99");
                return new AfterSaveResult() { CanExecute = false };
            }
            if (InternalApp.DebugMode)
            {
                EventBus.AddLog($"调试模式，调用打印任务编号{TaskNo} ");
                string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "config\\mainCode.btw"); //
                Dictionary<string, string> pairs = new Dictionary<string, string>();
                pairs.Add("mainCode", TaskNo);
                string printerName = AppSettings.GetConfig("PrinterName");
                _ = Task.Run(() =>
                {
                    try
                    {
                        PrinterHelper.PrinterLabel(filePath, printerName, pairs);
                    }
                    catch (Exception ex)
                    {
                        EventBus.AddError("打印出错了");
                    }
                });
            }
            else
            {
                string printResponse = WssPrintClient.PrintWaybill(task.WaybillNo);
            }

            
            EventBus.AddLog($"任务号{TaskNo}发送打印信息");
            task.StepNo = 4;
            task.Position = "升降贴标位";
            task.TaskStatus = TaskStatusType.打印面单完成;
            conn.Update<CksPackagingTask>().SetSource(task).ExecuteAffrows();

            dict["TaskNo"] = task.TaskNo;
            dict["WaybillNo"] = task.WaybillNo;
            dict["Info"] = "打印面单完成";
            dict["CheckResult"] = "1";
            UpdateDynamicTableData(fsqlTable, dict);
            return base.AfterSaved(e);
        }



    }
}
